//
// AWS Manager - A free AWS console application demonstrating advanced concepts
// Copyright (C) 2008-2010 Sean O'Dell. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/*
 * EBSAttachVolumes.java
 *
 * Created on Jul 31, 2008, 10:44:29 PM
 */
package awsmanager;

import com.awsmanager.common.AWSObjectUtils;
import com.awsmanager.common.EBSVolume;
import com.awsmanager.common.EC2Instance;
import com.sun.data.provider.RowKey;
import com.sun.rave.web.ui.appbase.AbstractPageBean;
import com.sun.webui.jsf.component.Alert;
import com.sun.webui.jsf.component.DropDown;
import com.sun.webui.jsf.component.Form;
import com.sun.webui.jsf.component.PageAlert;
import com.sun.webui.jsf.component.TabSet;
import com.sun.webui.jsf.component.TextField;
import com.sun.webui.jsf.model.Option;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import javax.faces.FacesException;
import javax.faces.component.html.HtmlInputTextarea;
import javax.faces.event.ValueChangeEvent;
import javax.faces.validator.LengthValidator;

/**
 * <p>Page bean that corresponds to a similarly named JSP page.  This
 * class contains component definitions (and initialization code) for
 * all components that you have defined on this page, as well as
 * lifecycle methods and event handlers where you may add behavior
 * to respond to incoming events.</p>
 *
 * @author Sean ODell
 */
public class EBSAttachVolumes extends AbstractPageBean {
    // <editor-fold defaultstate="collapsed" desc="Managed Component Definition">

    /**
     * <p>Automatically managed component initialization.  <strong>WARNING:</strong>
     * This method is automatically generated, so any user-specified code inserted
     * here is subject to being replaced.</p>
     */
    private void _init() throws Exception {
    }
    private DropDown ddl_InstanceIds = new DropDown();

    public DropDown getDdl_InstanceIds() {
        return ddl_InstanceIds;
    }

    public void setDdl_InstanceIds(DropDown dd) {
        this.ddl_InstanceIds = dd;
    }
    private Form form1 = new Form();

    public Form getForm1() {
        return form1;
    }

    public void setForm1(Form f) {
        this.form1 = f;
    }
    private HtmlInputTextarea ta_VolsList = new HtmlInputTextarea();

    public HtmlInputTextarea getTa_VolsList() {
        return ta_VolsList;
    }

    public void setTa_VolsList(HtmlInputTextarea hit) {
        this.ta_VolsList = hit;
    }
    private HtmlInputTextarea ta_DeviceList = new HtmlInputTextarea();

    public HtmlInputTextarea getTa_DeviceList() {
        return ta_DeviceList;
    }

    public void setTa_DeviceList(HtmlInputTextarea hit) {
        this.ta_DeviceList = hit;
    }
    private TextField tf_UsedDevices = new TextField();

    public TextField getTf_UsedDevices() {
        return tf_UsedDevices;
    }

    public void setTf_UsedDevices(TextField tf) {
        this.tf_UsedDevices = tf;
    }
    private LengthValidator lengthValidator1 = new LengthValidator();

    public LengthValidator getLengthValidator1() {
        return lengthValidator1;
    }

    public void setLengthValidator1(LengthValidator lv) {
        this.lengthValidator1 = lv;
    }
    private Alert al_EBSAttachVolumes = new Alert();

    public Alert getAl_EBSAttachVolumes() {
        return al_EBSAttachVolumes;
    }

    public void setAl_EBSAttachVolumes(Alert a) {
        this.al_EBSAttachVolumes = a;
    }
    private TextField tf_InstanceID = new TextField();

    public TextField getTf_InstanceID() {
        return tf_InstanceID;
    }

    public void setTf_InstanceID(TextField tf) {
        this.tf_InstanceID = tf;
    }
    private TextField tf_InstanceName = new TextField();

    public TextField getTf_InstanceName() {
        return tf_InstanceName;
    }

    public void setTf_InstanceName(TextField tf) {
        this.tf_InstanceName = tf;
    }
    protected Option[] instanceIDsOptions;

    /**
     * Get the value of instanceIDsOptions
     *
     * @return the value of instanceIDsOptions
     */
    public Option[] getInstanceIDsOptions() {
        return instanceIDsOptions;
    }

    /**
     * Set the value of instanceIDsOptions
     *
     * @param instanceIDsOptions new value of instanceIDsOptions
     */
    public void setInstanceIDsOptions(Option[] instanceIDsOptions) {
        this.instanceIDsOptions = instanceIDsOptions;
    }


    // </editor-fold>
    /**
     * <p>Construct a new Page bean instance.</p>
     */
    public EBSAttachVolumes() {
    }

    /**
     * <p>Callback method that is called whenever a page is navigated to,
     * either directly via a URL, or indirectly via page navigation.
     * Customize this method to acquire resources that will be needed
     * for event handlers and lifecycle methods, whether or not this
     * page is performing post back processing.</p>
     * 
     * <p>Note that, if the current request is a postback, the property
     * values of the components do <strong>not</strong> represent any
     * values submitted with this request.  Instead, they represent the
     * property values that were saved for this view when it was rendered.</p>
     */
    @Override
    public void init() {
        // Perform initializations inherited from our superclass
        super.init();
        // Perform application initialization that must complete
        // *before* managed components are initialized
        // TODO - add your own initialiation code here

        // <editor-fold defaultstate="collapsed" desc="Managed Component Initialization">
        // Initialize automatically managed components
        // *Note* - this logic should NOT be modified
        try {
            _init();
        } catch (Exception e) {
            log("EBSAttachVolumes Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e : new FacesException(e);
        }

    // </editor-fold>
    // Perform application initialization that must complete
    // *after* managed components are initialized
    // TODO - add your own initialization code here
    }

    /**
     * <p>Callback method that is called after the component tree has been
     * restored, but before any event processing takes place.  This method
     * will <strong>only</strong> be called on a postback request that
     * is processing a form submit.  Customize this method to allocate
     * resources that will be required in your event handlers.</p>
     */
    @Override
    public void preprocess() {
    }

    /**
     * <p>Callback method that is called just before rendering takes place.
     * This method will <strong>only</strong> be called for the page that
     * will actually be rendered (and not, for example, on a page that
     * handled a postback and then navigated to a different page).  Customize
     * this method to allocate resources that will be required for rendering
     * this page.</p>
     */
    @Override
    public void prerender() {

        String strVolList = new String();
        String strVolRef = new String();

        Map attachVolInfo = new HashMap(getSessionBean1().getAttachVolInfo());
        ArrayList attachVolList = new ArrayList((ArrayList) attachVolInfo.get("rowKeys"));

        for (int i = 0; i < attachVolList.size(); i++) {
            if (i > 0) {
                strVolList = strVolList + "\n";
            }
            EBSVolume ebsVolume = getSessionBean1().getEBSVolumeDataProvider().getVolume((RowKey) attachVolList.get(i));
            strVolRef = ebsVolume.getvolumeId().toString();
            if (ebsVolume.getvolname() != null) {
                if (!ebsVolume.getvolname().equals("")) {
                    strVolRef = strVolRef + " (" + ebsVolume.getvolname() + ")";
                }
            }
            if (strVolRef.length() > 60) {
                strVolRef = strVolRef.substring(0, 56) + "...)";
            }
            strVolList = strVolList + String.format("%-60s ", strVolRef);
            strVolList = strVolList + String.format("%5s GB", Integer.toString(ebsVolume.getsize()));
        }
        ta_VolsList.setValue(strVolList);
        ta_VolsList.setReadonly(true);

        // get a list of all instance ids
        ArrayList ec2instancelist =
                getSessionBean1().getEC2InstanceDataProvider().getEC2InstanceIDsList("running");

        // create the drop down list options from list of available
        // instance ids.
        instanceIDsOptions = new Option[ec2instancelist.size() + 1];
        instanceIDsOptions[0] = new Option("Select Instance ID");
        for (int i = 0; i < ec2instancelist.size(); i++) {
            EC2Instance ec2instance = getSessionBean1().getEC2InstanceDataProvider().getInstance((String) ec2instancelist.get(i));
            String strInstanceRef = new String((String) ec2instancelist.get(i));
            if (ec2instance.getinstname() != null) {
                if (!ec2instance.getinstname().equals("")) {
                    strInstanceRef = strInstanceRef + " (" + ec2instance.getinstname() + ")";
                }
            }
            instanceIDsOptions[i + 1] = new Option(strInstanceRef);
        }
    }

    /**
     * <p>Callback method that is called after rendering is completed for
     * this request, if <code>init()</code> was called (regardless of whether
     * or not this was the page that was actually rendered).  Customize this
     * method to release resources acquired in the <code>init()</code>,
     * <code>preprocess()</code>, or <code>prerender()</code> methods (or
     * acquired during execution of an event handler).</p>
     */
    @Override
    public void destroy() {
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected ApplicationBean1 getApplicationBean1() {
        return (ApplicationBean1) getBean("ApplicationBean1");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected RequestBean1 getRequestBean1() {
        return (RequestBean1) getBean("RequestBean1");
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected SessionBean1 getSessionBean1() {
        return (SessionBean1) getBean("SessionBean1");
    }

    public void ddl_InstanceIds_processValueChange(ValueChangeEvent event) {
        EC2Instance ec2instance = null;
        String instanceName = "";

        AWSObjectUtils awsObjectUtils = new AWSObjectUtils();
        String selectedInstanceID =
                awsObjectUtils.idExtract((String) ddl_InstanceIds.getSelected());

        ec2instance = getSessionBean1().getEC2InstanceDataProvider().getInstance((String) selectedInstanceID);

        if (ec2instance != null) {
            if ((instanceName = ec2instance.getinstname()) == null) {
                instanceName = "";
            }
        }

        Map volInfo = getSessionBean1().getEBSVolumeDataProvider().getVolInfoforInstance((String) selectedInstanceID);
        ArrayList deviceList = (ArrayList) volInfo.get("usedDeviceList");
        String deviceListStr = deviceList.toString().substring(1, deviceList.toString().length() - 1);

        tf_InstanceID.setText(selectedInstanceID);
        tf_InstanceName.setText(instanceName);
        tf_UsedDevices.setText(deviceListStr);

        if ((selectedInstanceID == null) || (selectedInstanceID.equals("")) || (selectedInstanceID.equals("Select Instance ID"))) {
            al_EBSAttachVolumes.setSummary("Please select an instance id from the list.");
        } else {
            al_EBSAttachVolumes.setSummary("");
        }

        form1.discardSubmittedValues("save");
    }

    /**
     * -----------------------------------------------------------------------
     */
    public String attachVolumes_action() {

        String strVolRef = new String();
        Map attachVolInfo = new HashMap(getSessionBean1().getAttachVolInfo());
        ArrayList attachDeviceList = new ArrayList();
        ArrayList attachVolList = new ArrayList((ArrayList) attachVolInfo.get("rowKeys"));

        EC2Instance ec2instance = null;
        String instanceName = new String();
        AWSObjectUtils awsObjectUtils = new AWSObjectUtils();
        String instanceID =
                awsObjectUtils.idExtract((String) ddl_InstanceIds.getSelected());

        if ((instanceID == null) || (instanceID.equals(""))) {
            al_EBSAttachVolumes.setSummary("Please select an instance id from the list.");
            return null;
        } else {
            ec2instance = getSessionBean1().getEC2InstanceDataProvider().getInstance(instanceID);
            if (ec2instance.getinstname() != null) {
                instanceName = ec2instance.getinstname();
            }
            al_EBSAttachVolumes.setSummary("");
        }

        try {
            attachDeviceList = (ArrayList) processTextArea(ta_DeviceList.getValue().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

        if ((attachDeviceList == null) || (attachDeviceList.isEmpty()) || (attachVolList.size() > attachDeviceList.size())) {
            al_EBSAttachVolumes.setSummary("Please enter device ids.");
            al_EBSAttachVolumes.setDetail("Enter corresponding list of devices ids, one for each volume. Number of devices must match the number of volumes.");
            return null;
        } else {
            al_EBSAttachVolumes.setSummary("");
        }

        String detailMessage = new String("Instance ID  : " + instanceID + "\n");
        detailMessage = detailMessage + "Instance Name: " + instanceName + "\n";
        detailMessage = detailMessage + String.format("%-70s %-6s\n", "Volume", "Device");
        detailMessage = detailMessage + String.format("%-70s %-6s\n", "------", "------");

        for (int i = 0; i < attachVolList.size(); i++) {
            if (i > 0) {
                detailMessage = detailMessage + "\n";
            }
            EBSVolume ebsVolume = getSessionBean1().getEBSVolumeDataProvider().getVolume((RowKey) attachVolList.get(i));
            strVolRef = ebsVolume.getvolumeId().toString();
            if (ebsVolume.getvolname() != null) {
                strVolRef = strVolRef + " (" + ebsVolume.getvolname() + ")";
                if (strVolRef.length() > 60) {
                    strVolRef = strVolRef.substring(0, 56) + "...)";
                }
            }
            detailMessage = detailMessage + String.format("%-60s ", strVolRef);
            detailMessage = detailMessage + String.format("%5s GB ", Integer.toString(ebsVolume.getsize()));
            detailMessage = detailMessage + String.format(" %s", attachDeviceList.get(i));
        }

        attachVolInfo = new HashMap();
        attachVolInfo.put("instanceID", instanceID);
        attachVolInfo.put("deviceList", attachDeviceList);
        attachVolInfo.put("rowKeys", attachVolList);

        getSessionBean1().setAttachVolInfo(attachVolInfo);

        PageAlert questionAlert = new PageAlert();
        questionAlert.setType("information");
        questionAlert.setTitle(" " + "Volumes will be attached!");
        questionAlert.setDetail("Volumes will be attached with the parameters listed below.");
        questionAlert.setSummary("Please press Continue to attach volumes.\nUse the scroll bar, if available, to view all.");

        getSessionBean1().setPageAlertAWSActionType("attachVolumes");
        getSessionBean1().setPageAlertDetailMessage(detailMessage);
        getSessionBean1().setUserPageAlert(questionAlert);
        getSessionBean1().setUserVisibleContinueBtn(true);
        getSessionBean1().setUserVisibleConnectBtn(false);
        return "attachVols";
    }

    public String cancelBtn_action() {
        TabSet tabSet = getSessionBean1().getCurrentTabSet();
        if (tabSet != null) {
            tabSet.setSelected("EBS_Volumes");
            getSessionBean1().setCurrentTabSet(tabSet);
        }
        return "cancel";
    }

    protected ArrayList processTextArea(String aLine) throws Exception {
        ArrayList attachDeviceList = new ArrayList();

        Scanner scanner = new Scanner(aLine);

        try {
            while (scanner.hasNextLine()) {
                try {
                    String deviceid = scanner.nextLine();
                    attachDeviceList.add(deviceid);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } finally {
            scanner.close();
        }
        return attachDeviceList;
    }
}